package ru.amse.jsynchro;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import ru.amse.jsynchro.GUI.ClientFrame;
import ru.amse.jsynchro.fileSystem.FileSystem;
import ru.amse.jsynchro.fileSystem.LocalFileSystem;
import ru.amse.jsynchro.kernel.task.IllegalTypeException;
import ru.amse.jsynchro.kernel.task.Task;
import ru.amse.jsynchro.kernel.task.TaskType;
import ru.amse.jsynchro.logging.LogFactory;
import ru.amse.jsynchro.net.server.SimpleServer;
import ru.amse.jsynchro.net.server.UserServer;

public class JSynchro {
    private static final String HELP_FILE_PATH = "help";

    /**
     * @param args
     */
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("must have args");
            printHelp();
            return;
        }
        String startArg = args[0];
        if (startArg.toLowerCase().equals("-help") 
                || startArg.toLowerCase().equals("help")
                || startArg.toLowerCase().equals("-h")) {
            printHelp();
            return;
        }
        if (startArg.equals("-server")) {
            String logging = args[1];
            UserServer server = new UserServer(LogFactory.getServerLogger(true, logging));
            server.start();
        } else 
            if (startArg.equals("-client")) {
                new ClientFrame();
        } else if (startArg.equals("-simple_server")) {
            if (checkSimpleServerParams(args)) {
                String logging = args[1];
                String folder = args[2];
                File folderFile = new File(folder);
                String userName = args[3];
                String userPassword = args[4];
                String stringPort = args[5];
                SimpleServer server = new SimpleServer(
                        LogFactory.getServerLogger(true, logging),
                        folderFile.getAbsolutePath(), userName, userPassword, 
                        Integer.parseInt(stringPort));
                server.start();
            }
        } else {    
            Task task = null;
            if (startArg.equals("-a") || startArg.equals("-s")) {
                String taskType = args[1];
                String sourceFolder = args[2];
                String destinationFolder = args[3];
                File folder1 = new File(args[2]);
                File folder2 = new File(args[3]);
                if (!(checkFolder(folder1) && checkFolder(folder2))) {
                    printHelp();
                    return;
                } else {
                    try {
                        FileSystem fs = new LocalFileSystem();
                        task = Task.createTask(sourceFolder, fs, 
                                destinationFolder, fs, false, 
                                new TaskType(taskType), 
                                LogFactory.getLocalLogger(true, "console_log"));
                    } catch (IOException e) {
                        System.out.println("can't access to directories, try again later");
                        e.printStackTrace();
                    } catch (IllegalTypeException ite) {
                        System.out.println("wrong synch type: " + taskType);
                        printHelp();
                    }
                    if (task == null) {
                        return;
                    }
                    task.analyze();
                    task.showDifferences();
                    if (startArg.equals("-s")) {
                        task.synchronize();
                    }
                    System.out.println("ok");
                }
            } else {
                System.out.println("wrong parameter: " + args[0]);
                printHelp();
            }
        }
    }    
    
    private static void printHelp() {
        try {
            InputStream in = ClassLoader.getSystemResourceAsStream(HELP_FILE_PATH);
//            ClassLoader.getSystemResourceAsStream(HELP_FILE_PATH);
            Reader r = new InputStreamReader(in);
            char[] c = new char[20];
            while (r.read(c) > -1) {
                System.out.print(c);
            }
        } catch(FileNotFoundException e) {
            System.out.println("can't find help file: " + HELP_FILE_PATH);
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("error reading help file");
            e.printStackTrace();
        }
        
    }
    
    public static boolean checkSimpleServerParams(String[] args) {
        if (args.length != 6) {
            System.out.println("no enough params");
            return false;
        }
        String folder = args[2];
        File folderFile = new File(folder);
        if (!checkFolder(folderFile)) {
            return false;
        }
        String stringPort = args[5];
        try {
            Integer.parseInt(stringPort);
        } catch (NumberFormatException e) {
            System.out.println("port must be a number");
            return false;
        }
        return true;
    }
   
    public static boolean checkFolder(File f) {
        if (!f.exists()) {
            System.out.println("folder " + f.getPath() + " does not exists!");
            return false;
        }
        if (!f.isDirectory()) {
            System.out.println("file " + f.getPath() + " is not a folder!");
            return false;
        }
        return true;
    }
}
